//
//  SXCollectionUnlimteImageScroll.m
//  SXCollectionViewImageCirculatePlay
//
//  Created by 98linju on 2017/7/27.
//  Copyright © 2017年 98linju. All rights reserved.
//

#import "SXCollectionUnlimteImageScroll.h"
#import "UIImageView+WebCache.h"

@interface SXCollectionUnlimteImageScroll ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>
//pageControl
@property (nonatomic,strong) UIPageControl *pageControl;
//轮播器 时间选择器
@property (nonatomic,strong) NSTimer *timer;
//数据源
@property (nonatomic,strong) NSMutableArray *netImageArr;
//视图CollectionView
@property (nonatomic,strong) UICollectionView *collectionView;
//展位图片
@property (nonatomic,strong) UIImage *placeholderImage;
//轮播器 间隔时间
@property (nonatomic,assign) CGFloat delayTime;
//当前 显示的是哪个item
@property (nonatomic,assign) NSInteger itemSelect;
/**判断是网络图片还是本地图片*/
@property (nonatomic,assign) BOOL isLoacalImageData;
@end
@implementation SXCollectionUnlimteImageScroll
static NSString *cellID= @"SXCollectionUnlimteImageScrollID";

- (instancetype) initWithFrame:(CGRect)frame netImageArr:(NSArray *)netImageArr placeholderImage:(UIImage *)placeholderImage delayTime:(CGFloat)delayTime pageCurrenTincolor:(UIColor *)pageCurrentColor pageTincolor:(UIColor *)tincolor{
    self = [super initWithFrame:frame];
    if (self) {
        _itemSelect = 1;
        self.placeholderImage = placeholderImage;
        self.delayTime = delayTime;
        //初始化数据
        [self inititalNetImageArr:[netImageArr copy]];
       //添加collectionView
        [self addCollectionViewAndLayoutCollcetionframe:frame];
        [self.collectionView registerClass:[SXCirculateCollectionCell class] forCellWithReuseIdentifier:cellID];
        
        //添加 pageControl
        CGFloat pagecontrolHeight = 30;
        CGFloat pageWidth = netImageArr.count * 20;
      self.pageControl = [self addPageControl:CGRectMake((frame.size.width - pageWidth)/2.0, frame.size.height - pagecontrolHeight, pageWidth, pagecontrolHeight) currentColor:pageCurrentColor tinColor:tincolor];
        [self addSubview:self.pageControl];
        [self addCirculateTimer];
        if (_netImageArr.count>1) {
            [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:_itemSelect inSection:0]
                                                atScrollPosition:UICollectionViewScrollPositionNone
                                                        animated:NO];
        }
    }
    
    return self;
}
/**
 * frame  轮播器frame
 * netImageArr  网络连接数据
 * placeholderImage  展位图片
 * delayTime  持续时间
 * pageCurrentColor  pageControl 滚动到的颜色
 * tincolor  pageControl 默认的颜色
 */
- (instancetype) initWithFrame:(CGRect)frame
                 localImageArr:(NSArray *)localImageArr
                     delayTime:(CGFloat)delayTime
            pageCurrenTincolor:(UIColor *)pageCurrentColor
                  pageTincolor:(UIColor *)tincolor{
    self = [super initWithFrame:frame];
    if (self) {
        _itemSelect = 1;
        self.delayTime = delayTime;
        //初始化数据
        [self inititalNetImageArr:[localImageArr copy]];
        //添加collectionView
        [self addCollectionViewAndLayoutCollcetionframe:frame];
        [self.collectionView registerClass:[SXCirculateCollectionCell class] forCellWithReuseIdentifier:cellID];
        self.isLoacalImageData = YES;
        //添加 pageControl
        CGFloat pagecontrolHeight = 30;
        CGFloat pageWidth = localImageArr.count * 20;
        self.pageControl = [self addPageControl:CGRectMake((frame.size.width - pageWidth)/2.0, frame.size.height - pagecontrolHeight, pageWidth, pagecontrolHeight) currentColor:pageCurrentColor tinColor:tincolor];
        [self addSubview:self.pageControl];
        [self addCirculateTimer];
        if (_netImageArr.count>1) {
            [self.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForItem:_itemSelect inSection:0]
                                        atScrollPosition:UICollectionViewScrollPositionNone
                                                animated:NO];
        }
    }
    
    return self;
}
//初始化数据
- (void) inititalNetImageArr:(NSArray *)netArr{
    self.netImageArr = [NSMutableArray array];
    [self.netImageArr addObject:netArr.lastObject];
    [self.netImageArr addObjectsFromArray:netArr];
    [self.netImageArr addObject:netArr.firstObject];
    NSLog(@"%@",self.netImageArr);
}
//添加 collectionView 和 layout
- (void)addCollectionViewAndLayoutCollcetionframe:(CGRect)frame{
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.itemSize = frame.size;
    flowLayout.minimumInteritemSpacing = 0;
    flowLayout.minimumLineSpacing = 0;
    flowLayout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    flowLayout.sectionInset = UIEdgeInsetsMake(0.f, 0.f, 0.f, 0.f);
   
    UICollectionView *collectionView = [[UICollectionView alloc] initWithFrame:frame collectionViewLayout:flowLayout];
    self.collectionView = collectionView;
    self.collectionView.showsHorizontalScrollIndicator = NO;
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    self.collectionView.pagingEnabled = YES;
    self.collectionView.bounces = NO;
    [self addSubview:self.collectionView];
}
//添加 pageControl
- (UIPageControl *) addPageControl:(CGRect)frame currentColor:(UIColor *)currentTinColor tinColor:(UIColor *)tinColor{
    self.pageControl = [[UIPageControl alloc] initWithFrame:frame];
    self.pageControl.currentPage = 0;
    self.pageControl.numberOfPages = _netImageArr.count - 2;
    
    self.pageControl.pageIndicatorTintColor = tinColor ? tinColor : [UIColor whiteColor];
    self.pageControl.currentPageIndicatorTintColor = currentTinColor ? currentTinColor:[UIColor lightGrayColor];
    return self.pageControl;
}
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return _netImageArr.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    SXCirculateCollectionCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:cellID forIndexPath:indexPath];
    if (self.isLoacalImageData) {//如果是网络数据
        cell.imageView.image = [UIImage imageNamed:self.netImageArr[indexPath.item]];
    }else{
        if (self.placeholderImage) {
            [cell.imageView sd_setImageWithURL:self.netImageArr[indexPath.item] placeholderImage:self.placeholderImage];
        }else{
            [cell.imageView sd_setImageWithURL:self.netImageArr[indexPath.item]];
        }
    }
   
    return cell;
}
- (void) collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if (self.selectedItemBlock) {
        dispatch_async(dispatch_get_main_queue(), ^{
            NSInteger itemIndex = indexPath.item;
            if (itemIndex == 0) {
                itemIndex = self.netImageArr.count - 2;
            }else if (itemIndex == self.netImageArr.count - 1) {
                itemIndex = 1;
            }
            self.selectedItemBlock(itemIndex);
        });
        
    }
}
//滚动将要减速的时候调用
- (void) scrollViewWillBeginDecelerating:(UIScrollView *)scrollView{
    
    [self invaliDateTimer];
    
}
//减速完毕的时候调用
- (void) scrollViewDidEndDecelerating:(UIScrollView *)scrollView{
    [self addCollectionViewItemSet];
    if (self.timer) {
        [self addCirculateTimer];
    }
}
//手动滑动的时候 重新设置 item 滚动位置
- (void) addCollectionViewItemSet{
    NSIndexPath *indexPath = [[self.collectionView indexPathsForVisibleItems] lastObject];
    NSLog(@"%ld",indexPath.item);
    self.itemSelect = indexPath.item;
    NSInteger toItem = 0;
    
    if (self.itemSelect == 0) {
        toItem = self.netImageArr.count-2;
        NSIndexPath *indexPath = [NSIndexPath indexPathForItem:toItem inSection:0];
        [self.collectionView scrollToItemAtIndexPath:indexPath
                                            atScrollPosition:UICollectionViewScrollPositionNone
                                                    animated:NO];
        self.itemSelect = toItem;
    }
    
    if (self.itemSelect == self.netImageArr.count-1) {
        toItem = 1;
        NSIndexPath *indexPath = [NSIndexPath indexPathForItem:toItem inSection:0];
        [self.collectionView scrollToItemAtIndexPath:indexPath
                                            atScrollPosition:UICollectionViewScrollPositionNone
                                                    animated:NO];
        self.itemSelect = toItem;
    }
    
    self.pageControl.currentPage = self.itemSelect-1;
}
//添加 时间选择器
- (void) addCirculateTimer{
    self.timer = [NSTimer scheduledTimerWithTimeInterval:self.delayTime target:self selector:@selector(circulateTimerChange:) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
}
//时间选择器方法
- (void) circulateTimerChange:(NSTimer *)timer{
    if (self.itemSelect == self.netImageArr.count-2) {
        NSInteger toItem = 0;
        NSIndexPath *indexPath = [NSIndexPath indexPathForItem:toItem inSection:0];
        [self.collectionView scrollToItemAtIndexPath:indexPath
                                            atScrollPosition:UICollectionViewScrollPositionNone
                                                    animated:NO];
        self.itemSelect = toItem;
    }
    
    self.itemSelect++;
    
    NSIndexPath *indexPath = [NSIndexPath indexPathForItem:self.itemSelect inSection:0];
    [self.collectionView scrollToItemAtIndexPath:indexPath
                                        atScrollPosition:UICollectionViewScrollPositionLeft
                                                animated:YES];
   
    self.pageControl.currentPage = self.itemSelect-1;
}
// 让 timer失效的方法
- (void)invaliDateTimer{
    if (self.timer) {
        [self.timer invalidate];
    }
}
- (void) setPageControlTincolor:(UIColor *)pageControlTincolor{
    _pageControlTincolor = pageControlTincolor;
    self.pageControl.pageIndicatorTintColor = pageControlTincolor;
}
- (void) setPageControlCurrentTincolor:(UIColor *)pageControlCurrentTincolor{
    _pageControlCurrentTincolor = pageControlCurrentTincolor;
    self.pageControl.currentPageIndicatorTintColor = pageControlCurrentTincolor;
}
- (void)dealloc{
    [self invaliDateTimer];
    self.timer = nil;
}
@end

@implementation SXCirculateCollectionCell
- (instancetype)initWithFrame:(CGRect)frame{
    self = [super initWithFrame:frame];
    if (self) {
        [self loadImageView];
    }
    return self;
}
- (void)loadImageView {
    if (!self.imageView) {
        self.imageView = [[UIImageView alloc] initWithFrame:self.bounds];
        self.imageView.backgroundColor = [UIColor whiteColor];
        [self.contentView addSubview:self.imageView];
    }
}
@end
